package com.hxd.mall.utils.open

import android.app.ActivityManager
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.util.Log
import java.util.*

/**
 * 扫描本地安装的应用(过滤系统应用),工具类
 */
object ApkTool {

    fun scanLocalInstallAppList(packageManager: PackageManager): List<MyAppInfo> {
        val myAppInfos = ArrayList<MyAppInfo>()
        try {
            val packageInfos =  packageManager.getInstalledPackages(0)
            for (i in packageInfos.indices) {
                val packageInfo = packageInfos[i] as PackageInfo
                //过滤掉系统app
                if (ApplicationInfo.FLAG_SYSTEM and packageInfo.applicationInfo.flags != 0) {
                    continue
                }
                myAppInfos.add(MyAppInfo(
                        packageInfo.applicationInfo.loadIcon(packageManager),
                        packageInfo.packageName,
                        packageInfo.applicationInfo.loadLabel(packageManager).toString()
                ))
            }
        } catch (e: Exception) {
            Log.e(javaClass.name, "===============获取应用包信息失败")
            throw e
        }
        return myAppInfos
    }

    data class MyAppInfo(var image: Drawable, var packageName: String, var appName: String)

    /**
     * 判断应用是否在前台
     */
    fun isForeground(context: Context?): Boolean {
        if (context != null) {
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val processes = activityManager.runningAppProcesses
            for (processInfo in processes) {
                if (processInfo.processName == context.packageName) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true
                    }
                }
            }
        }
        return false
    }


}
